package com.lxq.action;


import com.lxq.interceptor.TransactionValidator;
import com.lxq.model.Transaction;
import org.springframework.stereotype.Controller;
import org.springframework.validation.DataBinder;
import org.springframework.validation.Errors;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.validation.Valid;
import java.util.List;

@Controller
@RequestMapping("/validate")
public class TransactionController {
    @RequestMapping("/validator")
    public ModelAndView transvali(@Valid Transaction transaction, Errors errors){
        //检查是否存在错误
        if(errors.hasErrors()){
            List<FieldError> errorList=errors.getFieldErrors();
            for (FieldError fieldError : errorList) {
                System.out.println("错误字段"+fieldError.getField()+fieldError.getDefaultMessage());
            }
        }
        ModelAndView mv=new ModelAndView();
        mv.setViewName("welcome");
        return  mv;
    }
    //识别其他格式
    @InitBinder
    public void initBinder(DataBinder binder) {
        binder.setValidator(new TransactionValidator());
    }
}
